// src/features/language/languageSlice.ts
import { createSlice } from '@reduxjs/toolkit';

type LanguageState = {
  currentLanguage: 'zh' | 'en'; // 根据你的实际语言代码调整
};

// 从本地存储获取初始语言
const getInitialLanguage = (): LanguageState['currentLanguage'] => {
  if (typeof window !== 'undefined') {
    const savedLanguage = localStorage.getItem('language') as LanguageState['currentLanguage'] | null;
    if (savedLanguage) return savedLanguage;
    
    // 如果没有保存的语言，检查浏览器语言偏好
    const browserLanguage = navigator.language.split('-')[0];
    return browserLanguage === 'zh' ? 'zh' : 'en';
  }
  return 'zh'; // 默认语言
};

const initialState: LanguageState = {
  currentLanguage: getInitialLanguage()
};

const languageSlice = createSlice({
  name: 'language',
  initialState,
  reducers: {
    setLanguage: (state, action: { payload: LanguageState['currentLanguage'] }) => {
      state.currentLanguage = action.payload;
      localStorage.setItem('language', action.payload);
    },
    toggleLanguage: (state) => {
      state.currentLanguage = state.currentLanguage === 'zh' ? 'en' : 'zh';
      localStorage.setItem('language', state.currentLanguage);
    }
  }
});

export const { setLanguage, toggleLanguage } = languageSlice.actions;
export const selectCurrentLanguage = (state: { language: LanguageState }) => state.language.currentLanguage;
export default languageSlice.reducer;